Oops / Encapsulation / What is Static variables
Static Variable
-
Note
1. What is static variable
a static variable is a class-level variable that is used to share the data among all instances of a class. It belongs to the class, not to any single object.
the keyword "static " is used to declare a static variable
No object needed to access it
Access with class name
2. Difference between static and non-static variable
Features Static variable Non static variable Belongs To Class itself Each object (instance) Memory Allocation Only once, for the class Every time a new object is created Accessed With ClassName::$var or self::$var $this->var Shared Between Objects Yes No Needs Object to Access No Yes 3. When to Use Static Variables
All objects of a class needs to share a single copy of data
4. When not to use static variable
each object of a class needs to store its own data
Can we use static variable instead of non-static variables?
Technically yes, But you should not use static variable if you want to keep separate copy of value for each objects
Can we use non-static variable instead of static variables?
Technically yes, But objects can not share the data. Every object will get its own copy
MANVIA BLOG